package com.xunqi.permission.service;

import com.google.common.base.Preconditions;
import com.xunqi.permission.beans.PageQuery;
import com.xunqi.permission.beans.PageResult;
import com.xunqi.permission.common.RequestHolder;
import com.xunqi.permission.dao.SysUserMapper;
import com.xunqi.permission.pojo.SysUser;
import com.xunqi.permission.exception.ParamException;
import com.xunqi.permission.param.UserParam;
import com.xunqi.permission.util.BeanValidator;
import com.xunqi.permission.util.IpUtil;
import com.xunqi.permission.util.MD5Util;
import com.xunqi.permission.util.PasswordUtil;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysLogService sysLogService;

    public void save(UserParam param) {
        //使用BeanValidator工具类效验param是否有值
        BeanValidator.check(param);
        //判断传入的新增用户的电话是否被占用，使用id进行查询
        if (checkTelephoneExist(param.getTelephone(),param.getId())) {
            throw new ParamException("电话已被占用");
        }
        //判断传入的新增用户的邮箱是否被占用，使用id进行查询
        if (checkEmailExist(param.getMail(),param.getId())) {
            throw new ParamException("邮箱已被占用");
        }
        //生成随机密码
        String password = PasswordUtil.randomPassword();

        //使用MD5给密码加密
        String encryptedPassword = MD5Util.encrypt(password);
        //创建一个新的对象用来接收前台传来的用户的值
        SysUser user = SysUser.builder().username(param.getUsername()).telephone(param.getTelephone()).mail(param.getMail())
                .password(encryptedPassword).deptId(param.getDeptId()).status(param.getStatus()).remark(param.getRemark()).build();
        user.setOperator(RequestHolder.getCurrentUser().getUsername());
        user.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        user.setOperateTime(new Date());

        //调用用户新增方法
        sysUserMapper.insertSelective(user);
        //调用用户新增权限记录的方法
        sysLogService.saveUserLog(null,user);
    }


    public void update(UserParam param)  {
        BeanValidator.check(param);
        if (checkTelephoneExist(param.getTelephone(),param.getId())) {
            throw new ParamException("电话已被占用");
        }
        if (checkEmailExist(param.getMail(),param.getId())) {
            throw new ParamException("邮箱已被占用");
        }
        //根据传来的用户id进行查询，是否有该用户
        SysUser before = sysUserMapper.selectByPrimaryKey(param.getId());
        //若不存在则抛出异常
        Preconditions.checkNotNull(before,"待更新的用户不存在");
        SysUser after = SysUser.builder().id(param.getId()).username(param.getUsername()).telephone(param.getTelephone()).mail(param.getMail())
                .deptId(param.getDeptId()).status(param.getStatus()).remark(param.getRemark()).build();
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperateTime(new Date());
        sysUserMapper.updateByPrimaryKeySelective(after);
        sysLogService.saveUserLog(before,after);
    }

    @Cacheable(value = "checkEmailExist",keyGenerator = "keyGenerator")
    public boolean checkEmailExist(String mail,Integer userId) {
        return sysUserMapper.countByMail(mail,userId) > 0;
    }

    @Cacheable(value = "checkTelephoneExist",keyGenerator = "keyGenerator")
    public boolean checkTelephoneExist(String telephone,Integer userId) {
        return sysUserMapper.countByTelephone(telephone,userId) > 0;
    }

    public SysUser findByKeyWord(String keyWord) {
        return sysUserMapper.findByKeyword(keyWord);
    }


    @Cacheable(value = "getPageByDeptId",keyGenerator = "keyGenerator")
    //用户分页查询展示
    public PageResult<SysUser> getPageByDeptId(int deptId, PageQuery page) {
        BeanValidator.check(page);
        int count = sysUserMapper.countByDeptId(deptId);
        if (count > 0) {
            List<SysUser> list = sysUserMapper.getPageByDeptId(deptId, page);
            return PageResult.<SysUser>builder().total(count).data(list).build();
        }
        return PageResult.<SysUser>builder().build();
    }

    //获取所有信息
    @Cacheable(value = "getUserAll",keyGenerator = "keyGenerator")
    public List<SysUser> getAll() {
        return sysUserMapper.getAll();
    }

}
